<template>
  <el-container style="height: 100vh;">
    <el-main style="padding: 20px;">
      <!-- 查询条件 -->
      <div style="margin-bottom: 20px;">
        <el-input v-model="searchName" placeholder="请输入商品名" style="width: 200px; margin-right: 10px;"></el-input>
        <el-input-number v-model="priceRange.min" :min="0" placeholder="最低价格" style="width: 150px; margin-right: 10px;"></el-input-number>
        <el-input-number v-model="priceRange.max" :min="0" placeholder="最高价格" style="width: 150px;"></el-input-number>
      </div>

      <!-- 商品列表 -->
      <div>
        <h2>商品列表</h2>
        <el-button type="primary" @click="openAddDialog">上架商品</el-button>
        <el-row gutter="16">
          <el-col v-for="item in pagedGoodsList" :key="item.goodsId" :span="12">
            <el-card  :style="{ width: '787.5px', height: '304px' }">
              <template #header>
                {{ item.name }}
              </template>
              <el-row>
                <el-col :span="12">
                  <img :src="`http://192.168.239.53:8082/${item.imagePath}`" alt="商品图片" style="width: 100%; height: 200px; object-fit: cover; border-radius: 8px;"  />
                </el-col>
                <el-col :span="12" >
                  <p><strong>价格:</strong> ¥{{ item.price }}</p>
                  <p><strong>售卖人:</strong> {{ item.userId }}</p>
                  <p><strong>分类:</strong> {{ fetchCategoryname(item.categoryId) }}</p>
                  <div>
                    <el-button type="text" @click="openEditDialog(item)">编辑</el-button>
                    <el-button type="text" @click="deleteGoods(item.goodsId)">删除</el-button>
                    <el-button type="primary" @click="buyGoods(item.goodsId)">购买</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>

        <!--分页-->
      <el-pagination
  v-model:current-page="queryParams.pageNum"
  :page-size="queryParams.pageSize"
  :total="goodsList.length"  
  layout="prev, pager, next"
  @current-change="handlePageChange"
   class="pagination-bottom-right"  
  />
      </div>



      <!-- 添加或修改商品对话框 -->
      <el-dialog :title="dialogTitle" v-model="openDialog" width="500px" append-to-body>
        <el-form ref="goodsRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="商品名" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名" />
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input v-model="form.price" placeholder="请输入价格" />
          </el-form-item>
          <el-form-item label="图片" prop="imagePath">
          <el-upload
  action="http://192.168.239.53:8082/api/upload"
  :on-success="handleUploadSuccess"
  :on-error="handleUploadError"
  list-type="picture-card"
  :limit="1"
  :auto-upload="true"
  :before-upload="beforeUpload"
>
  <i class="el-icon-plus"></i>
</el-upload>

            <p v-if="form.imagePath">已上传图片：{{ form.imagePath }}</p>
          </el-form-item>
          <!-- 分类选择 -->
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="form.categoryId" placeholder="请选择分类">
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancelDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      goodsList: [], // 商品列表
      openDialog: false, // 对话框状态
      dialogTitle: "上架商品", // 对话框标题
      form: {
        goodsId: null,
        name: "",
        price: "",
        imagePath: "",
        userId: "当前用户 ID", // 模拟当前用户 ID
        categoryId: null, // 新增分类ID字段
        categoryname:null,
      }, // 表单数据
      rules: {
        name: [{ required: true, message: "请输入商品名", trigger: "blur" }],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        imagePath: [{ required: false, message: "请上传图片", trigger: "change" }],
        categoryId: [{ required: true, message: "请选择分类", trigger: "change" }],
      }, // 表单校验规则
      isEditMode: false, // 是否是编辑模式
      searchName: "", // 商品名查询条件
      priceRange: { min: 0, max: 10000 }, // 价格区间查询条件
      categories: [] ,// 存储分类数据
      queryParams: {
        pageNum: 1, // 当前页码
        pageSize: 4 , // 每页的商品数量
      },
      total: 0, // 商品总数
    };
  },
  computed: {
    // 根据商品名和价格区间筛选商品
    filterGoods() {
    return this.goodsList.filter(item => {
      const matchesName = item.name.toLowerCase().includes(this.searchName.toLowerCase());
      const matchesPrice = (this.priceRange.min ? item.price >= this.priceRange.min : true) &&
                            (this.priceRange.max ? item.price <= this.priceRange.max : true);
      return matchesName && matchesPrice;
    });
  },

  pagedGoodsList() {
    const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
    const end = start + this.queryParams.pageSize;
    return this.filterGoods.slice(start, end);  // 使用总商品数据，不是筛选后的数据
  }
  },

  
  
  methods: {

    // 获取 Token
    getToken() {
      return sessionStorage.getItem('authToken') || ''; // 从 localStorage 获取 Token
    },

    // 设置请求头中的认证信息
    setAuthHeaders() {
      const token = this.getToken();
      if (token) {
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      }
    },

  buyGoods(goodsId) { 
  this.$confirm("确认购买此商品吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios.delete(`http://192.168.239.53:8082/goods/buy/${goodsId}`, {
       
      })
        .then((response) => {

            this.goodsList = this.goodsList.filter((item) => item.goodsId !== goodsId);
            this.$message.success("购买成功！");
        })
        .catch((error) => {
          console.error('Error deleting goods:', error);
          this.$message.error('购买商品失败');
        });
    })
    .catch(() => {
      this.$message.info("已取消购买");
    });
},
   
// 获取商品列表
getGoodsList() {
  const token = sessionStorage.getItem('token');  // Get the token from sessionStorage

  if (!token) {
    // If token is not found, prompt user to log in
    this.$message.error('未登录，请先登录');
    this.$router.push('/login');  // Redirect to login page
    return;
  }

  axios.get('http://192.168.239.53:8082/goods', {
    headers: {
      Authorization: `Bearer ${token}`  // Add token to request headers
    },
    params: {
      page: this.queryParams.pageNum, // Use `this.queryParams.pageNum`
      size: this.queryParams.pageSize, // Use `this.queryParams.pageSize`
    },
  })
  .then(response => {
    console.log('Received data:', response.data);  // Log the response data
    if (Array.isArray(response.data.data)) {
      this.goodsList = response.data.data.map(item => ({
        goodsId: item.id,
        name: item.goodsName,
        price: item.price,
        imagePath: item.goodsPic,
        userId: item.userId,
        goodsTime: item.goodsTime,
        categoryId: item.categoryId
      }));
      this.total = response.data.data.total || 0; // Total number of items
    } else {
      this.goodsList = [];
      this.total = 0;
      this.$message.error('获取商品列表失败：数据格式不正确');
    }
  })
  .catch(error => {
    console.error('Error fetching goods list:', error);
    this.$message.error('获取商品列表失败');
  });
},


  // 获取 Token
  getToken() {
    return sessionStorage.getItem('token'); // 从 localStorage 获取 token
 },

  // 设置请求头中的认证信息
  setAuthHeaders() {
    const token = this.getToken();
    if (token) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    }
  },

    // 获取分类列表
    fetchCategories() {
      this.setAuthHeaders(); // 每次请求前设置 Token
      axios.get('http://192.168.239.53:8082/category')
        .then(response => {
          if (response.data.code === 1) {
            this.categories = response.data.data;
          } else {
            this.$message.error('获取分类列表失败');
          }
        })
        .catch(error => {
          console.error('Error fetching categories:', error);
          this.$message.error('获取分类列表失败');
        });
    },

    //获取分类名称
    fetchCategoryname(categoryId) {
  const category = this.categories.find(item => item.id === categoryId);
  return category ? category.name : "未知分类";
},


    //分页
   //分页
 handlePageChange(page) {
      this.queryParams.pageNum = page;
    },



    // 打开添加商品对话框
    openAddDialog() {
      this.isEditMode = false;
      this.dialogTitle = "上架商品";
      this.form = { goodsId: null, name: "", price: "", imagePath: "", userId: "当前用户 ID", categoryId: null };
      this.openDialog = true;
    },

    // 打开编辑商品对话框
    openEditDialog(item) {
    this.isEditMode = true;
    this.dialogTitle = "编辑商品";
    this.form = { ...item }; // 将选中的商品信息填入表单
    this.openDialog = true;
  },

    // 上传成功处理
   handleUploadSuccess(response) {
  console.log('Upload Success Response:', response);  // 打印响应，检查返回的数据
  if (response && response.data) {
    // 假设返回的是文件名
    const fileName = response.data;  // 获取文件名（后端返回的是文件名）
    const baseURL = 'http://192.168.239.53:8082/upload/';  // 假设图片存放在这个目录下
    this.form.imagePath = fileName;  // 拼接完整的图片路径
    this.$message.success("图片上传成功！");
  } else {
    this.$message.error("图片上传失败，服务器未返回文件路径！");
  }
},
    // 上传失败处理
    handleUploadError() {
      this.$message.error("图片上传失败，请稍后重试！");
    },

    // 提交表单
 submitForm() {
  this.$refs.goodsRef.validate((valid) => {
    if (valid) {
      // 格式化请求数据为后端所需的格式
      const postData = {
        goodsName: this.form.name,  // 前端的 name -> 后端的 goodsName
        price: parseFloat(this.form.price),  // 确保价格是数字
        categoryId: this.form.categoryId,  // 分类 ID
        goodsId: this.form.goodsId,  // 确保传递 goodsId
        goodsPic: this.form.imagePath,  // 确保提交时有正确的图片路径
      };

      console.log('Post Data:', postData);  // 打印提交的数据，检查 imagePath 是否正确

      if (this.isEditMode) {
        // 编辑商品：更新商品信息
        this.setAuthHeaders(); // 设置 Token
        axios.put(`http://192.168.239.53:8082/goods/${this.form.goodsId}`, postData, {
          headers: {
            Authorization: `Bearer ${this.getToken()}`  // 确保请求头中有 Token
          }
        })
          .then(response => {
            const index = this.goodsList.findIndex(item => item.goodsId === this.form.goodsId);
            if (index !== -1) {
              // 只更新该商品的属性，不替换整个商品对象
              this.goodsList[index] = {
                ...this.goodsList[index],  // 保留原有属性
                ...this.form,              // 更新需要修改的属性
              };
              this.$message.success("商品信息已更新！");
            }
            this.openDialog = false; // 关闭对话框
          })
          .catch(error => {
            console.error('Error updating goods:', error);
            this.$message.error('更新商品失败');
          });
      } else {
        // 添加商品：新增商品
        this.setAuthHeaders(); // 设置 Token
        axios.post('http://192.168.239.53:8082/goods', postData, {
          headers: {
            Authorization: `Bearer ${this.getToken()}`  // 确保请求头中有 Token
          }
        })
          .then(response => {
            if (response.data && response.data.id) {
              const newGoods = {
                goodsId: response.data.id,
                name: response.data.goodsName,
                price: response.data.price,
                imagePath: response.data.goodsPic, // 如果后端返回了图片路径，可以设置
                userId: response.data.userId,
                goodsTime: response.data.goodsTime,
                categoryId: response.data.categoryId
              };
              this.goodsList.push(newGoods); // 将新商品添加到列表中
              this.$message.success("商品已成功上架！");
            } 
            this.openDialog = false; // 关闭对话框
            this.getGoodsList();
          })
          .catch(error => {
            console.error('Error adding goods:', error);
            this.$message.error('添加商品失败！');
          });
      }
    } else {
      this.$message.error("请填写完整信息！");
    }
  });
},


    // 删除商品
   deleteGoods(goodsId) {
  this.$confirm("确认删除此商品吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      this.setAuthHeaders(); // 设置 Token
      axios.delete(`http://192.168.239.53:8082/goods/${goodsId}`, {
        headers: {
          Authorization: `Bearer ${this.getToken()}`  // 确保请求头中有 Token
        }
      })
        .then((response) => {
          // 如果返回的 code 是 1，则表示删除成功
          if (response.data.code === 1) {
            // 从商品列表中删除该商品
            this.goodsList = this.goodsList.filter((item) => item.goodsId !== goodsId);
            this.$message.success("商品已删除！");
          } else if (response.data.code === 0) {
            // 如果返回的 code 是 0，表示没有删除权限
            this.$message.error(response.data.msg || "您没有删除此商品的权限！");
          } else {
            this.$message.error(response.data.msg || "删除商品失败");
          }
        })
        .catch((error) => {
          console.error('Error deleting goods:', error);
          this.$message.error('删除商品失败');
        });
    })
    .catch(() => {
      this.$message.info("已取消删除");
    });
},



    // 取消对话框
    cancelDialog() {
      this.openDialog = false;
    },

    //上传令牌
    beforeUpload(file) {
    const token = sessionStorage.getItem('token');  // 从 sessionStorage 获取令牌
    console.log('获取的 token:', token);  // 打印令牌，检查它是否有效
    if (token) {
      // 设置请求头中的令牌
      file.headers = {
        Authorization: `Bearer ${token}`,
      };
      return true; // 继续上传
    } else {
      this.$message.error('未登录，请先登录');
      return false; // 如果没有令牌，则阻止上传
    }
   },
  },
  mounted() {
    // 获取商品列表和分类列表数据
    this.getGoodsList();
    this.fetchCategories(); // 加载分类
  }
};
</Script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
.pagination-bottom-right {
  position: absolute;
  bottom: 20px;
  right: 20px;
}
</style>
